<template>
  <div class="app-container">
        <el-form
          ref="editActivityData"
          :rules="rules"
          :model="editActivityData"
          class="addTictStyle"
          label-position="top"
        >
          <el-row :gutter="24">
            <el-col :span="16" :offset="4">
              <h3 class="ticTitle">基本信息：</h3>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="16" :offset="4">
              <el-form-item label="活动名称 :" prop="activactivityName">
                <el-input v-model="editActivityData.activityName" placeholder="请输入票务名称" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="16" :offset="4">
              <el-form-item label="活动起始时间 :" prop="startTime">
                <el-date-picker
                  v-model="editActivityData.startTime"
                  type="date"
                  placeholder="选择日期"
                  style="width:100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="16" :offset="4">
              <el-form-item label="活动终止时间 :" prop="endTime">
                <el-date-picker
                  v-model="editActivityData.endTime"
                  type="date"
                  placeholder="选择日期"
                  style="width:100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="16" :offset="4">
              <el-form-item label="活动头图 :" prop="code">
                <el-upload
                  ref="detailUpload"
                  action="''"
                  list-type="picture-card"
                  :file-list="detailShowImgs"
                  :auto-upload="false"
                  :on-remove="detailRemove"
                  :http-request="uploadFileDeatail"
                >
                  <i class="el-icon-plus" />
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="24">
            <el-col :span="16" :offset="4">
              <el-form-item label="活动背景 :" prop="yardactivactivityName">
                <el-upload
                  ref="upload"
                  action="''"
                  list-type="picture-card"
                  :file-list="showImgs"
                  :auto-upload="false"
                  :http-request="uploadFile"
                  :on-remove="handleRemove"
                >
                  <i class="el-icon-plus" />
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="16" :offset="4">
              <el-form-item label="描述 :" prop="activityDescrption">
                <el-input v-model="editActivityData.activityDescrption" type="textarea" placeholder="选择场地后自动填充" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="16" :offset="4">
              <h4 class="ticTitle">分享设置: </h4>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="16" :offset="4">
              <el-form-item label="投放渠道">
                <el-checkbox-group v-model="editActivityData.investChannal">
                  <el-checkbox v-for="invest in investChannalOption" :label="invest.code" :key="invest.code">{{invest.name}}</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="16" :offset="4">
              <el-form-item label="用户分享 :" prop="userShare">
                <el-switch
                  v-model="editActivityData.activityUserShare"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                  active-value="100"
                  inactive-value="0"
                  @change="checkRecedeTick"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="16" :offset="4">
              <el-form-item v-if="this.editActivityData.activityUserShare==100" label="分享标题 :" prop="activityShareTitle">
                <el-input v-model="editActivityData.activityShareTitle" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="16" :offset="4">
              <el-form-item v-if="this.editActivityData.activityUserShare==100" label="分享图片 :" prop="shareImg">
                <el-upload
                  ref="carouseUpload"
                  action="''"
                  list-type="picture-card"
                  :file-list="carouselShowImgs"
                  :auto-upload="false"
                  :http-request="uploadFileCarouse"
                >
                  <i class="el-icon-plus" />
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="24">
            <el-col :span="16" :offset="4">
              <el-form-item v-if="this.editActivityData.activityUserShare==100" label="分享文案 :" prop="activityShareOffical">
                <el-input v-model="editActivityData.activityShareOffical" type="textarea" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="16" :offset="4">
              <h4 class="ticTitle">关联设置: </h4>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="16" :offset="4">
              <el-form-item label="关联优惠券 :" prop="activityRelevance">
                <el-select v-model="editActivityData.activityRelevance" filterable placeholder="请票据状态" style="width:100%">
                  <el-option
                    v-for="item in couponData"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                    {{ item.name }}
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-footer height="80px">
            <el-row style="display: flex;justify-content: center;align-items: center;">
              <el-button @click="submit" type="primary">
                保存
              </el-button>
              <el-button @click="editOut">
                取消
              </el-button>
            </el-row>
          </el-footer>
        </el-form>
  </div>
</template>

<script>
import { replaceSpacesObj } from '../../../utils/webUtils.js'
import {} from '../../../styles/addTict.scss'

export default {
  name: 'EditTict',
  components: {},
  props: {
    tictUuid: {
      type: String
    }
  },
  data() {
    return {
      couponData:[],
      uuid: this.tictUuid,
      editActivityData: {
        id:'',
        activityName: '',
        startTime: '',
        endTime: '',
        activityImgStr:'',
        activityHeadImgStr:'',
        activityDescrption: '',
        activityUserShare: '',
        activityShareTitle: '',
        activityShareOffical: '',
        activityShareImgStr: '',
        activityRelevance: '',
        investChannal:[],
      },
      investChannalOption:[],
      showImgs: [],
      list: [],
      detailShowImgs: [],
      detailList: [],
      carouselShowImgs: [],
      carouseList: [],
      validOptions: {},
      yardOptions: [],
      mercList: [],
      validationOptions: [],
      tickValue: [],
      merchants: { name: '', uuid: '' },
      rules: {
      },
      info: '',
      infoShow: false,
      editBoxShow: false,
      editShow: false,
      tictObj: {}
    }
  },
  // 深度监听父组件的props传值
  watch: {
    tictUuid(val) {
      this.uuid = val
      this.queryActivity();
    }
  },
  mounted() {
    this.uuid=this.$route.params.uuid
    console.log("uuid"+this.uuid)
    this.queryCouponData()
    this.queryTeamCus()
    this.queryActivity()
  },
  methods: {
    queryTeamCus() {
      this.axios
        .request({
          method: 'get',
          url: './kwp/kdi/para/code/TCK_GRANT_CANNAL',
          params: {}
        })
        .then(response => {
          this.investChannalOption = response.data.subParas
        })
        .catch(error => {
          console.log(error)
        })
    },
    // 查询所有优惠券
    queryCouponData() {
      this.axios.request({
        method: 'get',
        url: './coupon/coupon/template/listTemplate',
      }).then(response => {
        this.couponData = response.data.data
      }).catch(error => {
        console.log(error)
      })

    },
    carouseRemove(file, fileList) {
      console.log(file)
      console.log(fileList)
      for (var i in this.fileList) {
        if (fileList[i].uid == file.uid) {
          var count = --i;
          fileList.splice(count, 1);

        }
      }
      this.carouselShowImgs=fileList
      if(this.carouselShowImgs.length>0) {
        this.carouselShowImgs.forEach(res => {
          this.carouseList.push({'filename': res.name, 'url': res.url.substr(res.url.lastIndexOf('activity'))})
        })
        this.editActivityData.activityShareImgStr = JSON.stringify(this.carouseList)
      }else{
        this.editActivityData.activityShareImgStr =''
      }
    },
    detailRemove(file, fileList) {
      console.log(file)
      console.log(fileList)
      for (var i in this.fileList) {
        if (fileList[i].uid == file.uid) {
          var count = --i;
          fileList.splice(count, 1);

        }
      }
      this.detailShowImgs=fileList
      this.detailList=[]
      if (this.detailShowImgs.length>0){
        this.detailShowImgs.forEach(res=>{
          this.detailList.push({'filename':res.name,'url':res.url.substr(res.url.lastIndexOf('activity'))})
        })
        this.editActivityData.activityHeadImgStr=JSON.stringify(this.detailList)
      }else{
        this.editActivityData.activityHeadImgStr=''
      }
    },
    handleRemove(file, fileList) {
      for (var i in this.fileList) {
        if (fileList[i].uid == file.uid) {
          var count = --i;
          fileList.splice(count, 1);
        }
      }
        this.showImgs=fileList
      this.list=[]
      if(this.showImgs.length>0) {
        this.showImgs.forEach(res => {
          this.list.push({'filename': res.name, 'url': res.url.substr(res.url.lastIndexOf('activity'))})
        })
        this.editActivityData.activityImgStr = JSON.stringify(this.list)
      }else{
        this.editActivityData.activityImgStr=''
      }

    },
    imgState(msg) {
      this.editBoxShow = msg
      this.editShow = msg
      // this.queryActivity();
    },
    // 监听
    checkRecedeTick() {
      if (this.editActivityData.activityUserShare == '0') {
        this.editActivityData.shareTitle = ''
        this.editActivityData.activityShareImgStr = ''
        this.editActivityData.shareOffical = ''
        this.$refs.carouseUpload.clearFiles();

      }
    },

    // 通过uuid查询当前对象信息
    queryActivity() {
      this.axios.request({
        method: 'get',
        url: './tck/activity/' + this.uuid,
        headers: {},
        params: {}
      }).then(response => {
        this.insertTict(response.data.data)
      }).catch(error => {
        console.log(error)
      })
    },
    insertTict(activity) {
      this.editActivityData.activityName = activity.activityName
      this.editActivityData.startTime = activity.startTime
      this.editActivityData.endTime = activity.endTime
      this.editActivityData.activityImgStr = activity.activityImgStr
      this.editActivityData.activityDescrption = activity.activityDescrption
      this.editActivityData.activityUserShare = activity.activityUserShare
      this.editActivityData.activityShareTitle = activity.activitySharetitle
      this.editActivityData.activityShareImgStr = activity.activityShareImgStr
      this.editActivityData.activityShareOffical = activity.activityShareOffical
      this.editActivityData.activityRelevance = activity.activityRelevance
      this.editActivityData.activityHeadImgStr=activity.activityHeadImgStr
      this.editActivityData.investChannal=JSON.parse(activity.investChannal)
      this.editActivityData.id=activity.id
      this.quertImgRelook()
    },
    submit() {
      if(this.editActivityData.investChannal!=null&&this.editActivityData.investChannal!=''){
        this.editActivityData.investChannal=JSON.stringify(this.editActivityData.investChannal)
      }
      this.$refs['editActivityData'].validate((valid) => {
        if (!valid) {
          return
        }
        this.axios.request({
          method: 'put',
          url: './tck/activity/updateActivity',
          headers: {
            'Content-Type': 'application/json;charset=UTF-8'
          },
          data: replaceSpacesObj(this.editActivityData)
        }).then((response) => {
          this.tictObj = response.data
          this.dataSucess("修改数据成功");
          this.imgSubmit();
          this.editOut()
        }).catch(error => {
          console.log(error)
          this.info = '修改失败'
          this.infoShow = true
          this.dataFail();

        })
      })
    },
    uploadFileCarouse(item){
      if(item.file!=null&&item.file!=''){
      let formData = new FormData();
      formData.append('upFile', item.file);
      this.axios.post(
        "./tck/activity/upload/img/"+this.uuid,formData
      ).then(res=>{
        var data=res.data.data;
        this.carouseList.push({'filename':data.filename,'url':data.url})

        this.editActivityData.activityShareImgStr = JSON.stringify(this.carouseList)
        if(this.editActivityData.activityShareImgStr.length>0){
          this.uploadImg();
        }
      }).catch(error => {
        console.log(error);
        this.dataFail("上传分享图片失败")
      });
      }else{
        this.editActivityData.activityShareImgStr=''
      }
    },
    uploadFile(item){
      if(item.file!=null&&item.file!=''){
      let formData = new FormData();

      formData.append('upFile', item.file);
      this.axios.post(
        "./tck/activity/upload/img/"+this.uuid,formData
      ).then(res=>{
        var data=res.data.data;
        this.list.push({'filename':data.filename,'url':data.url})

        this.editActivityData.activityImgStr = JSON.stringify(this.list)
        if(this.editActivityData.activityImgStr.length>0){
          this.uploadImg();
        }

      }).catch(error => {
        this.dataFail("上传活动背景失败")
      });
      }else{
        this.editActivityData.activityImgStr = ''
      }
    },
    uploadFileDeatail(item){
      if(item.file!=null&&item.file!=''){
      let formData = new FormData();
      formData.append('upFile', item.file);
      this.axios.post(
        "./tck/activity/upload/img/"+this.uuid,formData
      ).then(res=>{
        var data=res.data.data;
        this.detailList.push({'filename':data.filename,'url':data.url})
        this.editActivityData.activityHeadImgStr = JSON.stringify(this.detailList)
        if(this.editActivityData.activityHeadImgStr.length>0){
          this.uploadImg();
        }
      }).catch(error => {
        console.log(error);
        this.dataFail("上传活动头图失败")
      });
      }else{
        this.editActivityData.activityHeadImgStr=''
      }
    },
    imgSubmit(){
      if(this.showImgs.length>0) {
        this.showImgs.forEach(res => {
          this.list=[]
          this.list.push({'filename': res.name, 'url': res.url.substr(res.url.lastIndexOf('activity'))})
        })
        this.editActivityData.activityImgstr = JSON.stringify(this.list)
      }else{
        this.editActivityData.activityImgStr=''
      }
      if (this.detailShowImgs.length>0){
        this.detailList=[]
        this.detailShowImgs.forEach(res=>{
          this.detailList.push({'filename':res.name,'url':res.url.substr(res.url.lastIndexOf('activity'))})
        })
        this.editActivityData.activityHeadImgStr=JSON.stringify(this.detailList)
      }else{
        this.editActivityData.activityHeadImgStr=''
      }
      if(this.carouselShowImgs.length>0) {
        this.carouseList=[]
        this.carouselShowImgs.forEach(res => {
          this.carouseList.push({'filename': res.name, 'url': res.url.substr(res.url.lastIndexOf('activity'))})
        })
        this.editActivityData.activityShareImgStr = JSON.stringify(this.carouseList)
      }else{
        this.editActivityData.activityShareImgStr =''
      }
      this.$refs.detailUpload.submit()
      this.$refs.upload.submit()
      if(this.editActivityData.activityUsershare!='0'&&this.editActivityData.activityUsershare!=null&&this.editActivityData.activityUsershare!='') {
        this.$refs.carouseUpload.submit()
      }


    },

    dataSucess(message) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success'
      });
    },
    dataFail(message) {
      this.$notify({
        title: '失败',
        message: message,
        type: 'error'
      });
    },
    //图片回显
    quertImgRelook(){
      if(this.editActivityData.activityImgStr != null && this.editActivityData.activityImgStr != ''){
        this.showImgs = [];
        JSON.parse(this.editActivityData.activityImgStr).forEach(res=>{
          this.showImgs.push({'name':res.filename,'url':"http://39.106.30.94/respu/"+res.url})
        })
      }
      if(this.editActivityData.activityHeadImgStr != null && this.editActivityData.activityHeadImgStr != '') {
        this.detailShowImgs=[]
        JSON.parse(this.editActivityData.activityHeadImgStr).forEach(res => {
          this.detailShowImgs.push({'name': res.filename, 'url': "http://39.106.30.94/respu/" + res.url})
        })
      }
      if(this.editActivityData.activityShareImgStr != null && this.editActivityData.activityShareImgStr != '') {
        this.carouselShowImgs=[]
        JSON.parse(this.editActivityData.activityShareImgStr).forEach(res => {
          this.carouselShowImgs.push({'name': res.filename, 'url': "http://39.106.30.94/respu/" + res.url})
        })
      }
    },
    //图片上传
    uploadImg(){
      this.axios.request({
        method: "put",
        url: "./tck/activity/updateActivity",
        headers: {
          "Content-Type": "application/json;charset=UTF-8"
        },
        data: replaceSpacesObj(this.editActivityData)
      }).then(() => {
      }).catch(error => {
        console.log(error);
        this.info = '上传图片后回写imgStr数据失败！';
        this.infoShow = true;
        this.dataFail("上传图片回写数据失败")
      });
    },
    cleanTict() {
      this.$router.push('/tictReport/')
    },

    endProcessing() {
      this.info = this.info + '修改成功,两秒后关闭'
      this.infoShow = true
      setTimeout(() => {
        this.infoShow = false
        this.$emit('editState', false)
        this.cleanTict()
        this.info = ''
      }, 2000)
    },
    cleanActivity() {
      this.editActivityData = {
        activityName: '',
        startTime: '',
        endTime: '',
        activityImgStr: '',
        activityDescrption: '',
        activityUsershare: '',
        activitySharetitle: '',
        activityShareoffical: '',
        activityRelevance: '',
        activityHeadImgStr:'',
      }
    },
    editOut() {
  this.$router.push("/ticActivity")
    }
  }
}
</script>

<style scoped>
  .edit {
    width: 100%;
    height: 100%;
    z-index: 100;
  }

</style>
